<template>
  <page-container :title="$route.meta.title">
    <search-form :model="searchForm" @search="handleSearch" @reset="handleReset">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="任务名称" prop="jobName">
            <el-input v-model="searchForm.jobName" placeholder="请输入任务名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="任务组名" prop="jobGroup">
            <el-input v-model="searchForm.jobGroup" placeholder="请输入任务组名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态" prop="status">
            <el-select v-model="searchForm.status" placeholder="请选择状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="运行中" value="1"></el-option>
              <el-option label="已暂停" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" class="search-buttons">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
      </el-row>
    </search-form>

    <div class="table-container">
      <el-button 
        type="primary" 
        icon="el-icon-plus" 
        @click="handleAdd"
        v-permission="'job:add'"
      >
        新增任务
      </el-button>
      
      <el-table
        :data="jobList"
        border
        stripe
        style="width: 100%; margin-top: 15px;"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="jobName" label="任务名称" min-width="150"></el-table-column>
        <el-table-column prop="jobGroup" label="任务组名" min-width="120"></el-table-column>
        <el-table-column prop="jobClassPath" label="执行类路径" min-width="250"></el-table-column>
        <el-table-column prop="cronExpression" label="Cron表达式" min-width="180"></el-table-column>
        <el-table-column prop="parameter" label="任务参数" min-width="150"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <job-status-tag :status="scope.row.status"></job-status-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160" :formatter="formatDate"></el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template slot-scope="scope">
            <el-button 
              size="mini" 
              type="text" 
              @click="handleEdit(scope.row)"
              v-permission="'job:edit'"
            >
              编辑
            </el-button>
            <el-button 
              size="mini" 
              type="text" 
              :disabled="scope.row.status === 1"
              :type="scope.row.status === 0 ? 'success' : 'warning'"
              @click="handleStartOrPause(scope.row)"
              v-permission="'job:start' || 'job:pause'"
            >
              {{ scope.row.status === 0 ? '启动' : '暂停' }}
            </el-button>
            <el-button 
              size="mini" 
              type="text" 
              @click="handleRunOnce(scope.row)"
              v-permission="'job:run'"
            >
              立即执行
            </el-button>
            <el-button 
              size="mini" 
              type="text" 
              style="color: #f56c6c" 
              @click="handleDelete(scope.row)"
              v-permission="'job:delete'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :current-page="pagination.pageNum"
        :page-size="pagination.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 15px; text-align: right;"
      ></el-pagination>
    </div>
  </page-container>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import PageContainer from '@/components/common/PageContainer.vue'
import SearchForm from '@/components/common/SearchForm.vue'
import JobStatusTag from '@/components/job/JobStatusTag.vue'

export default {
  name: 'JobList',
  components: {
    PageContainer,
    SearchForm,
    JobStatusTag
  },
  data() {
    return {
      searchForm: {
        jobName: '',
        jobGroup: '',
        status: ''
      },
      pagination: {
        pageNum: 1,
        pageSize: 10
      },
      loading: false
    }
  },
  computed: {
    ...mapState({
      jobList: state => state.job.jobList,
      total: state => state.job.total
    })
  },
  methods: {
    ...mapActions({
      getJobList: 'job/getJobList',
      startJob: 'job/startJob',
      pauseJob: 'job/pauseJob',
      runJobOnce: 'job/runJobOnce',
      deleteJob: 'job/deleteJob'
    }),
    
    // 格式化日期
    formatDate(row, column, cellValue) {
      return this.$options.filters.formatDate(cellValue)
    },
    
    // 搜索
    handleSearch() {
      this.pagination.pageNum = 1
      this.loadJobList()
    },
    
    // 重置
    handleReset() {
      this.searchForm = {
        jobName: '',
        jobGroup: '',
        status: ''
      }
      this.pagination.pageNum = 1
      this.loadJobList()
    },
    
    // 加载任务列表
    loadJobList() {
      this.loading = true
      const params = {
        ...this.searchForm,
        ...this.pagination
      }
      this.getJobList(params).finally(() => {
        this.loading = false
      })
    },
    
    // 新增任务
    handleAdd() {
      this.$router.push('/job/add')
    },
    
    // 编辑任务
    handleEdit(row) {
      this.$router.push(`/job/edit/${row.id}`)
    },
    
    // 启动/暂停任务
    handleStartOrPause(row) {
      if (row.status === 0) {
        this.$confirm(`确定要启动任务【${row.jobName}】吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          this.startJob(row.id).then(() => {
            this.$message.success('任务启动成功')
            this.loadJobList()
          })
        })
      } else {
        this.$confirm(`确定要暂停任务【${row.jobName}】吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.pauseJob(row.id).then(() => {
            this.$message.success('任务暂停成功')
            this.loadJobList()
          })
        })
      }
    },
    
    // 立即执行一次
    handleRunOnce(row) {
      this.$confirm(`确定要立即执行任务【${row.jobName}】吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'question'
      }).then(() => {
        this.runJobOnce(row.id).then(() => {
          this.$message.success('任务已触发执行')
          this.loadJobList()
        })
      })
    },
    
    // 删除任务
    handleDelete(row) {
      this.$confirm(`确定要删除任务【${row.jobName}】吗？此操作不可恢复！`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.deleteJob(row.id).then(() => {
          this.$message.success('任务删除成功')
          this.loadJobList()
        })
      })
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadJobList()
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.pageNum = val
      this.loadJobList()
    }
  },
  created() {
    this.loadJobList()
  }
}
</script>

<style scoped>
.table-container {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 25px;
}
</style>
